package com.cgc.venus.server.core.k8s.impl;

import com.cgc.venus.server.core.exception.VenusException;
import com.cgc.venus.server.core.k8s.inter.K8sConfigMapService;
import io.fabric8.kubernetes.api.model.ConfigMap;
import io.fabric8.kubernetes.api.model.ConfigMapList;
import io.fabric8.kubernetes.api.model.DoneableConfigMap;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.dsl.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xyr on 2017/9/19.
 * kubernetes 配置管理对象操作接口实现
 */

@Service
public class K8sConfigMapServiceImpl implements K8sConfigMapService {
    @Autowired
    private KubernetesClient k8sClient;

    /*
    * 获得全部空间的配置集
    * 返回的json格式
    * [
            {
                "configMapName": "yk-aly-configmap",
                "createTime": "2017-09-20 11:22:33",
                "files": {
                    "items": [
                        {
                            "configMapName": "yk-aly-configmap ",
                            "fileContent": "22222222222222222222",
                            "fileName": "config.txt",
                            "namespace": "default"
                        }
                    ],
                    "total": 100
                },
                "namespace": "default"
            }
        ]
    * */
    @Override
    public List<Map<String, Object>> getConfigMap(String namespace) throws VenusException {
        List<Map<String,Object>> mapList = new ArrayList<Map<String, Object>>();
        ConfigMapList configMapList = null;
        if (StringUtils.isNotBlank(namespace)){
            // 查询指定空间
            configMapList = k8sClient.configMaps().inNamespace(namespace).list();
        } else {
            // 查询全部空间
            configMapList = k8sClient.configMaps().list();
        }
        List<ConfigMap> configMaps = configMapList.getItems();
        int size = configMaps.size();

        for (int i = 0; i < size; i++) {
            ConfigMap configMap = configMaps.get(i);
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("configMapName",configMap.getMetadata().getName());
            map.put("createTime",configMap.getMetadata().getCreationTimestamp().replaceAll("T"," ").replaceAll("Z",""));
            map.put("namespace",configMap.getMetadata().getNamespace());
            List<Map<String,Object>> itemList = new ArrayList<Map<String, Object>>();

            // 得到文件列表
            Map<String,String> dataMap = configMap.getData();
            if (dataMap != null) {
                for (Map.Entry<String,String> entry : dataMap.entrySet()) {
                    Map<String,Object> fileMap = new HashMap<String, Object>();
                    fileMap.put("fileName",entry.getKey());
                    fileMap.put("fileContent",entry.getValue());
                    fileMap.put("configMapName",configMap.getMetadata().getName());
                    fileMap.put("namespace",configMap.getMetadata().getNamespace());

                    // 放到items
                    itemList.add(fileMap);
                }
            }

            Map<String,Object> filesMap = new HashMap<String, Object>();
            filesMap.put("items",itemList);
            filesMap.put("total",itemList.size());

            map.put("files",filesMap);
            mapList.add(map);
        }
        return mapList;
    }

    @Override
    public ConfigMapList getConfigMaps(String namespace) throws VenusException {
        ConfigMapList configMapList = k8sClient.configMaps().inNamespace(namespace).list();
        return configMapList;
    }

    /*
    * 查询配置集
    * */
    @Override
    public ConfigMap queryConfigMap(String namespace, String configMapName) throws VenusException {
        Resource<ConfigMap,DoneableConfigMap> resource = k8sClient.configMaps().inNamespace(namespace).withName(configMapName);
        ConfigMap configMap = resource.get();
        return configMap;
    }

    /*
   * 创建配置集
   * */
    @Override
    public ConfigMap addConfigMap(String namespace, String configMapName) throws VenusException {
        ConfigMap configMap = new ConfigMap();
        configMap.setKind("ConfigMap");
        configMap.setApiVersion("v1");

        // 元数据
        ObjectMeta objectMeta = new ObjectMeta();
        // 配置集名
        objectMeta.setName(configMapName);
        // 配置集所属的命名空间
        objectMeta.setNamespace(namespace);
        configMap.setMetadata(objectMeta);
        // 创建
        ConfigMap configMap1 = k8sClient.configMaps().create(configMap);
        return configMap1;
    }

    /*
    * 判断配置集里面是否存在相同的配置文件
    * */
    @Override
    public boolean existConfigFile(String namespace, String configMapName, String fileName) throws VenusException {
        ConfigMap configMap = queryConfigMap(namespace,configMapName);
        Map<String,String> map = configMap.getData();
        if (map != null) {
            for (Map.Entry<String,String> m : map.entrySet()) {
                if (m.getKey().equals(fileName)) {
                    return true;
                }
            }
        }
        return false;
    }

    /*
    * 往配置集里面添加配置文件
    * */
    @Override
    public ConfigMap addConfigFile(String namespace, String configMapName, String fileName, String fileContent) throws VenusException {
        ConfigMap configMap = k8sClient.configMaps().inNamespace(namespace).withName(configMapName).edit()
                .addToData(fileName,fileContent).done();
        return configMap;
    }

    /*
    * 删除配置集中的单个文件
    * */
    @Override
    public ConfigMap deleteConfigFile(String namespace, String configMapName, String fileName) throws VenusException {
        ConfigMap configMap = k8sClient.configMaps().inNamespace(namespace).withName(configMapName).edit()
                .removeFromData(fileName).done();
        return configMap;
    }

    /*
    * 删除配置集中多个文件
    * */
    @Override
    public ConfigMap batchDeleteConfigFile(String namespace, String configMapName, Map<String, String> filesMap) throws VenusException {
        ConfigMap configMap = k8sClient.configMaps().inNamespace(namespace).withName(configMapName).edit()
                .removeFromData(filesMap).done();
        return configMap;
    }

    /*
    * 删除整个配置集
    * */
    @Override
    public boolean deleteConfigMap(String namespace, String configMapName) throws VenusException {
        boolean delete = k8sClient.configMaps().inNamespace(namespace).withName(configMapName).delete();
        return delete;
    }

    @Override
    public String getConfigFileContent(String namespace, String configMapName, String fileName) {
        return null;
    }
}
